package com.xzz.mybatis.generator.common;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.xzz.mybatis.generator.utils.MyBeanUtil;
import com.xzz.mybatis.generator.utils.MyCollectionUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Set;

/**
 * @author: hhz
 * @createDate: 2021-3-29
 */
@Slf4j
public class MyBaseServiceImpl<M extends BaseMapper<T>, T> extends ServiceImpl<M, T>  {
    //为了解决sonnar扫描，M泛型必须使用
    @Override
    public M getBaseMapper() {
        return baseMapper;
    }

    protected <T> List<T> toEntityList(List list, Class<T> entityClass) {
        if (MyCollectionUtil.isEmptyOrNull(list)) return Lists.newArrayList();
        Class sourceClass = list.get(0).getClass();
        return MyBeanUtil.copyListShallow(list, sourceClass, entityClass);
    }

    protected <T> List<T> toDtoList(List list, Class<T> dtoClass) {
        if (MyCollectionUtil.isEmptyOrNull(list)) return Lists.newArrayList();
        Class sourceClass = list.get(0).getClass();
        return MyBeanUtil.copyListShallow(list, sourceClass, dtoClass);
    }

    protected <T> Set<T> toDtoSet(Set set, Class<T> dtoClass) {
        if (MyCollectionUtil.isEmptyOrNull(set)) return Sets.newHashSet();
        Class sourceClass = set.iterator().next().getClass();
        return MyBeanUtil.copySetShallow(set, sourceClass, dtoClass);
    }

    protected <T> T toDto(Object source, Class<T> dtoClass) {
        T targetObj = null;
        if (null == source) return targetObj;
        try {
            targetObj = dtoClass.newInstance();
            MyBeanUtil.copyShallow(source, targetObj);
        } catch (IllegalAccessException | InstantiationException e) {
            log.warn("invoke toDto get error", e);
        }
        return targetObj;
    }

    protected <T> T toEntity(Object source, Class<T> entityClass) {
        T targetObj = null;
        if (null == source) return targetObj;
        try {
            targetObj = entityClass.newInstance();
            MyBeanUtil.copyShallow(source, targetObj);
        } catch (IllegalAccessException | InstantiationException e) {
            log.warn("invoke toEntity get error", e);
        }
        return targetObj;
    }
}
